/**
 * @module initWebSocket 初始化
 * @module websocketonopen 连接成功
 * @module websocketonerror 连接失败
 * @module websocketclose 断开连接
 * @module resetHeart 重置心跳
 * @module sendSocketHeart 心跳发送
 * @module reconnect 重连
 * @module sendMsg 发送数据
 * @module websocketonmessage 接收数据
 * @module test 测试收到消息传递
 * @description socket 通信
 * @param {any} url socket地址
 * @param {any} websocket websocket 实例
 * @param {any} heartTime 心跳定时器实例
 * @param {number} socketHeart 心跳次数
 * @param {number} HeartTimeOut 心跳超时时间
 * @param {number} socketError 错误次数
 */

import useToken from "@/hooks/useToken";

export let socketUrl: any = "ws://127.0.0.1:8080/resource/websocket"; // socket地址
let websocket: any = null; // websocket 实例
let heartTime: any = null; // 心跳定时器实例
let socketHeart = 0 as number; // 心跳次数
const HeartTimeOut = 10000; // 心跳超时时间 10000 = 10s
let socketError = 0 as number; // 错误次数
let webSocketInstance: null = null;

// 初始化socket
export const initWebSocket = (url: any) => {
	const { token } = useToken();
	if (import.meta.env.VITE_APP_WEBSOCKET === "false") {
		return;
	}
	if (!webSocketInstance) {
		socketUrl = url;
		// 初始化 websocket
		websocket = new WebSocket(url + "?Authorization=Bearer " + token + "&clientid=" + import.meta.env.VITE_GLOB_CLIENT_ID);
		websocket.onopen = () => {
			console.log("连接打开");
			resetHeart();
		};
		websocket.onclose = (e: any) => {
			console.log("断开连接", e);
		};
		websocket.onerror = (error: any) => {
			console.log("连接 websocket 失败", error);
		};
		websocket.onmessage = (event: { data: any }) => {
			console.log("Received message:", event.data);
			handleMessage(event.data);
		};
	}
};

// socket 重置心跳
export const resetHeart = () => {
	socketHeart = 0;
	socketError = 0;
	clearInterval(heartTime);
	sendSocketHeart();
};
//发送心跳
export const sendSocketHeart = () => {
	heartTime = setInterval(() => {
		// 如果连接正常则发送心跳
		if (websocket.readyState == 1) {
			websocket.send(
				JSON.stringify({
					type: "ping"
				})
			);
			socketHeart = socketHeart + 1;
		} else {
			// 重连
			reconnect();
		}
	}, HeartTimeOut);
};

// socket重连
export const reconnect = () => {
	if (socketError <= 2) {
		clearInterval(heartTime);
		initWebSocket(socketUrl);
		socketError = socketError + 1;
		console.log("socket重连", socketError);
	} else {
		console.log("重试次数已用完");
		clearInterval(heartTime);
	}
};
export const handleMessage = (e: any) => {
	if (e.data.indexOf("heartbeat") > 0) {
		resetHeart();
	}
	if (e.data.indexOf("ping") > 0) {
		return;
	}
	console.log(e);
	return e.data;
};
export const getWebSocketInstance = () => {
	return webSocketInstance;
};
